﻿using System;
using System.Web.Mvc;
using Web7.Core.Apps;
using Web7.Core.Extensions;
using Web7.Core.Security;
using Microsoft.Practices.Unity;

namespace Web7.Core.ActionFilters.Authorization
{
    public class AdvancedAuthorizationFilter : IAuthorizationFilter
    {
        private readonly IDependencyResolver _dependencyResolver;
        private readonly Func<IAuthorizer, bool> _checkUser;

        public IAuthorizer Authorizer
        {
            get { return _dependencyResolver.GetService<IAuthorizer>(); }
        }

        public IAuthenticationService AuthenticationService
        {
            get { return _dependencyResolver.GetService<IAuthenticationService>(); }
        }

        public AdvancedAuthorizationFilter(Func<IAuthorizer, bool> checkUser)
            : this(DependencyResolver.Current, checkUser) { }

        public AdvancedAuthorizationFilter(IDependencyResolver dependencyResolver, Func<IAuthorizer, bool> checkUser)
        {
            if (dependencyResolver == null)
                throw new ArgumentNullException("dependencyResolver");
            if (checkUser == null)
                throw new ArgumentNullException("checkUser");

            _dependencyResolver = dependencyResolver;
            _checkUser = checkUser;
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!_checkUser(Authorizer))
            {
                string signInUrl = AuthenticationService.GetSigInUrl();
                filterContext.SetActionResult(signInUrl);
            }

        }
    }
}
